package com.gg.goods;

import com.gg.entity.Fruit;
import com.gg.helper.DBHelper;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "GetFruitsByCidServlet", value = "/goods/GetFruitsByCidServlet")
public class GetFruitsByCidServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*获取请求参数c_id*/
        String c_id = request.getParameter("c_id");


        /*创建一个Fruit 集合*/
        List<Fruit> fruits = new ArrayList<>();
        /*1.数据库 连接*/
        Connection con = DBHelper.getConnection();
        /*2. SQL */
        String sql = "select *  from fruit where c_id = ?";
        /*3. 发射器*/
        try {
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, c_id);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                int f_id = rs.getInt("f_id");
                String f_name = rs.getString("f_name");
                String f_norm = rs.getString("f_norm");
                BigDecimal f_price = rs.getBigDecimal("f_price");
                String f_summary = rs.getString("f_summary");
                String f_prompt = rs.getString("f_prompt");
                int f_imgcount = rs.getInt("f_imgcount");
                c_id = rs.getString("c_id");
                boolean f_entrance = rs.getBoolean("f_entrance");
                boolean f_hot = rs.getBoolean("f_hot");
                //恢复一个水果
                Fruit fruit = new Fruit(f_id, f_name, f_norm, f_price, f_summary, f_prompt, f_imgcount, c_id, f_entrance, f_hot);
                //把这个恢复出来的水果放集合里
                fruits.add(fruit);
            }
            /*把20个水果的   集合fruits 放Session里， 跳转页面到sel.jsp页面显示*/
            request.getSession().setAttribute("fruits", fruits);
            response.sendRedirect("/fruit/sel.jsp");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }


}
